package time.after.time.sys.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.codec.Base64;

import time.after.time.ssf.work.PropertyFilter.PropertyType;
import time.after.time.ssf.work.ReflectionUtils;


public class Utils
{

	public static String encodeBase64(String val)
	{
		return new String(Base64.encode(val.getBytes()));
	}
	
	public static String decodeBase64(String val)
	{
		return new String(Base64.decode(val.getBytes()));
	}
	
	/**
	 * 转换为百分率
	 * @param n
	 * @return
	 */
    public static String toPercentage(double n)
    {
        double m = n * 100D;
        DecimalFormat df = new DecimalFormat("###.0");
        return df.format(m);
    }
    /**
     * 批量整型数组转换为String--List
     * 
     * 去除重复的int值
     */
    public static List<String> toUniqueStringList(List<Integer> list)
    {
    	List<String> _list=new ArrayList<String>();
    	if(list==null||list.size()==0)
    		return _list;
    	for(Integer integer : list) 
    	{
    		String val=String.valueOf(integer);
    		if(_list.contains(val))
    			continue;
    		_list.add(val);
		}
    	return _list;
    }
    
    /**
     * 是空或者0以下
     */
    public static boolean isNullOr0_(Integer _i)
    {
    	return parseInteger(_i)<1;
    }
    
    public static int parseInteger(Integer _i)
    {
    	return _i==null?0:_i.intValue();
    }
    public static int parseInteger(Integer _i,Integer defaultVal)
    {
    	return _i==null?defaultVal:_i.intValue();
    }
    public static long parseLong(Long _i)
    {
    	return _i==null?0l:_i.longValue();
    }    
    /**
     * 指定模式将字符串转换为long数组
     * @param regex 字符串分隔符
     * @return
     */
    public static int[] toIntArray(String val,String regex)
    {
		String[] array=val.split(",");
		int[] _ls=new int[array.length];
		for(int i = 0; i < array.length; i++)
		{
			_ls[i]=Integer.parseInt(array[i]);
		} 
		return _ls;
    }
    
    public static Long[] toLongArray(String[] array)
    {
    	Long[] _ls=new Long[array.length];
		for(int i = 0; i < array.length; i++)
		{
			_ls[i]=Long.parseLong(array[i]);
		} 
		return _ls;
    }
    
    /**
     * 取小数点后二位
     * @return
     */
    public static String get2Bit(double val)
    {
    	  BigDecimal bd=  new BigDecimal(val);   
    	  bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);  
    	  return bd.toString();
    }
   	/**
	 * 美式格式数据
	 * 
	 * @param source
	 *            3453454
	 * @return 3,453,454
	 */
	public static String num2US(long source) {
		NumberFormat usFormat = NumberFormat.getIntegerInstance(Locale.US);
		return usFormat.format(source);
	}
    
	/**
	 * 显示文件大小
	 * @param size
	 * @return
	 */
	public static String getHumanReadableFilesize(double size)
	{
	   String[] units = new String[]{"B","KB","MB","GB","TB","PB"};
	   double mod = 1024.0;
	   int i=0;
	   while(size >= mod) 
	   {
	      size /= mod;
	      i++;
	    }
	   return get2Bit(size) + units[i];
	}
	
	public static String formatDateTime(Date myDate, String pattern) {
		SimpleDateFormat fd = new SimpleDateFormat(pattern);
		return (fd.format(myDate));
	}
	/**
	 * 返回当前时间yyyy-MM-dd格式 
	 */
	public static String getSimpleDate()
	{
	   return formatDateTime(new Date(),"yyyy-MM-dd");
	}
	/**
	 * 返回当前时间yyyy-MM-dd HH:mm:ss 格式
	 */
	public static String getNow()
	{
	   return formatDateTime(new Date(),"yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 检查是否已过一天[最小检查单位天]
	 * 适用一天内只能触发一次事件检测
	 * @param dateStr 
	 * @return true 已过一天
	 */
	public static boolean checkOneDayPast(String dateStr) {
		return  formatStrDate(getSimpleDate()).getTime()- formatStrDate(dateStr).getTime() >= 24 * 3600 * 1000;
	}
	
	/**
	 * Str格式时间转换为DATE格式
	 * @param dateStr
	 * @return
	 */
	public static Date formatStrDate(String dateStr) {
		Date date = null;
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = sf.parse(dateStr);
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	
	public static boolean isFullDate(String value)
	{
		return isDate(value,"yyyy-MM-dd HH:mm:ss");
	}
	
	public static boolean isDate(String value,String format)
	{  
		SimpleDateFormat sdf = null;
		ParsePosition pos = new ParsePosition(0);// 指定从所传字符串的首位开始解析
		if (value == null || StringUtils.isEmpty(format)) {
			return false;
		}
		try {
			sdf = new SimpleDateFormat(format);
			sdf.setLenient(false);
			Date date = sdf.parse(value, pos);
			if (date == null) {
				return false;
			} else {

				// 更为严谨的日期,如2011-03-024认为是不合法的
				if (pos.getIndex() > sdf.format(date).length()) {
					return false;
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
    }  	
	
	
	
	/**
	 * 简化StringBuilder append 操作 
	 */
	public static StringBuilder appendAll(StringBuilder builder,Object ...obj)
	{
		for(Object _s:obj) builder.append(_s);
		return builder;
	}  
	
	/**
	 * 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从0开始.
	 */	
	public static int getFirst(int pageNo,int pageSize) {
		return ((pageNo - 1) * pageSize);
	}	
	
	/**
	 * 根据pageSize与totalCount计算总页数, 默认值为-1.
	 */
	public static int getTotalPages(int totalCount,int pageSize)
	{
		if (totalCount < 0)
			return -1;
		int count = totalCount / pageSize;
		if (totalCount % pageSize > 0)
			count++;
		return count;
	}
	
	/**
	 *  获取完整来源URL 包括请求参数转换为GET方式 
	 */
	public static String getManaUrl(String url,HttpServletRequest request)
	{
		Enumeration paramNames = request.getParameterNames();
		while(paramNames != null && paramNames.hasMoreElements())
		{
			String paramName = (String) paramNames.nextElement();
			String[] values = request.getParameterValues(paramName);
			String _val="";
			if (values == null || values.length == 0) { 
				continue;
			} else if (values.length > 1) {
				try {
					_val=Mapper.writeValueAsString(values);
				} catch (Exception e){}
			} else {
				_val=values[0];
			}
			String str=paramName.concat("=").concat(_val);
			if(url.indexOf("?") > -1) {
				url += "&" + str;
			} else {
				url += "?" + str;
			}		
		}
		return url; 
	 }
	/**
	 * Map 多key删除
	 */
	public static Map<String,Object> removeKeys(Map<String,Object> map,String ...keys)
	{
		for(String key : keys) 
		{
			map.remove(key);
		}
		return map;
	}
	
	
	
	/**
     * 分页显示类
     * 
     * @author Aliyador in 2010-11-22
     *
     */
    public static class PaginationHelper
    {
    	/**  配置项  **/
    	 static final String UNCLICK_TAG_CSS="dis_page";      //不能点击的class名设置
    	 static final String JS_DEFAULT_FUNCTION="jumpPage";  //默认跳转调用JS
    	 
      	/**
      	 * 前端显示分页 (默认回调JS名jumpPage)
      	 * @param curPage  当前页
      	 * @param totalPage 总页数
      	 * @param totals 总记录数
      	 * @return
      	 */          	
     	public static String getPageLinkStr(int curPage,int totalPage,int totals)
     	{
     		return getPageLinkStr(JS_DEFAULT_FUNCTION, curPage, totalPage,totals,true);
     	}
     	
     	/**
     	 * 前端显示分页
     	 * @param functionName 前端调用JS名字
     	 * @param curPage  当前页
     	 * @param totalPage 总页数
     	 * @param totals 总记录数
     	 * @return
     	 */     	
    	public static String getPageLinkStr(String functionName,int curPage,int totalPage,int totals)
    	{
    		return getPageLinkStr(functionName,curPage,totalPage,totals,true);
    	}
     	
     	/**
     	 * 前端显示分页
     	 * @param functionName 前端调用JS名字
     	 * @param curPage  当前页
     	 * @param totalPage 总页数
     	 * @param totals 总记录数
     	 * @param quickPageQuery 快速页码查询
     	 * @return
     	 */
    	public static String getPageLinkStr(String functionName,int curPage,int totalPage,int totals,boolean quickPageQuery)
    	{
    		if(StringUtils.isEmpty(functionName))
    			functionName=JS_DEFAULT_FUNCTION;
            if(totalPage <2)
            	return "";
    		int max = 3;
    		StringBuilder builder=new StringBuilder(); 
    		builder.append("<span style='cursor:default'>共有 <label class='total_records'>"+totals+"</label> 条记录</span>");
    		if (curPage>1)
    		{
    			builder=appendAll(builder,"<a href='#' onclick='javascript:",functionName,"(",(curPage - 1),");return false;'><span>上一页</span></a>");
    		}
    		
    		if (curPage - max > 1)
    		{
    			
    			builder=appendAll(builder,"<a href='#' onclick=\"",functionName,"(1);return false;\"><span>1</span></a>");
    			if(curPage!=max+2)
    			  builder=appendAll(builder,"<span class='etc'>...</span>");
    		}
    		for(int i=1;i <= totalPage;i++)
    		{
    			if (i <= curPage + max && i >= curPage - max)
    			{
    				if (i == curPage)
    				{
    					builder=appendAll(builder,"<span class='current'>",i,"</span>");
    				}
    				else
    				{
    					builder=appendAll(builder,"<a href='#' onclick=\"",functionName,"(",i,");return false;\"><span>",i,"</span></a>");
    				}
    			}
    		}
    		if(curPage + max < totalPage)
    		{
    			if(totalPage!=curPage+max+1)
    			  builder.append("<span class='etc'>...</span>");
    			builder=appendAll(builder,"<a href='#' onclick=\"",functionName,"(",totalPage,");return false;\"><span>",totalPage,"</span></a>");
    		}
    		if(curPage != totalPage)
    		{
    			builder=appendAll(builder,"<a href='#' onclick='javascript:",functionName,"(",(curPage + 1),");return false;'><span>下一页</span></a>");
    		}
    		builder.append("</ul>");
    		
    		if(quickPageQuery)
    		{
        		builder=appendAll(builder,"<form><span>到第<input type='text' class='goto onlyNum' id='jump2sw' maxlength='5'>页</span>&nbsp;"
        				,"<input type='button' class='submit' value='确认' onclick=\"javascript:var _jump2Page=document.getElementById('jump2sw').value;_jump2Page=_jump2Page.length==0?1:_jump2Page;",functionName,"(_jump2Page);\"></form>");
    		}
    		
    		return builder.toString();
    	}	
    }
    
    public static class ManaHelper
    {
    	/**
    	 * 根据按PropertyFilter命名规则的Request参数,创建PropertyFilter列表.
    	 * PropertyFilter命名规则为 类型属性类型_属性名.
    	 * 
    	 */
    	@SuppressWarnings("unchecked")
    	public static Map<String,Object> buildManaProperty(final HttpServletRequest request, final String manaPrefix)
    	{
    		Map<String,Object> _return=new HashMap<String, Object>();
    		Map<String, String> manaParamMap = ServletUtils.getParametersStartingWith(request, manaPrefix);
    		for(Map.Entry<String, String> entry : manaParamMap.entrySet())
    		{
    			String manaName = entry.getKey();
    			String value = entry.getValue();
    			//如果value值为空,则忽略此filter.
    			if (StringUtils.isNotBlank(value))
    			{
    				Mana m =buildMana(manaName, value);
    				_return.put(m.paramName,m.paramValue);
    			}
    		}
    		return _return;
    	}

       private static Mana buildMana(String manaName,String value)
       {
    	  Mana mana=new Mana();
    	  Class<?> propertyType = null;
   		  String propertyTypeCode = StringUtils.substringBefore(manaName, "_");
		  try {
			propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
		  } catch (RuntimeException e) {
			throw new IllegalArgumentException("mana名称" + manaName + "没有按规则编写,无法得到属性值类型.", e);
		  }
		  mana.paramName = StringUtils.substringAfter(manaName, "_");
		  mana.paramValue = ReflectionUtils.convertStringToObject(value, propertyType);   	   
    	  return mana;
       }
    }
    
	public static void main(String[] args) {
		System.out.println(new String(Base64.encode(String.valueOf(1).getBytes())));
		System.out.println(new String(Base64.decode("MQ==".getBytes())));
//		Base64.decode(base64DataBC, decodedDataCC)
	}
}

class Mana {
    public String paramName;
    public Object paramValue;
}
